﻿#pragma once

#include<vector>

//仿函数: 转换为无符号整型
template<class K>
struct HashFunc
{
	size_t operator()(const K& key)
	{
		return (size_t)key;
	}
};

//特化: 将string类转换为无符号整型
template<>	
struct HashFunc<string>
{
	size_t operator()(const string& s)
	{
		//BKDR哈希算法
		size_t hash = 0;
		for (auto ch : s)
		{
			hash += ch;
			hash *= 131;
		}

		return hash;
	}
}	;

//素数表函数：用于哈希表初始化和扩容（取大于n的最小素数）
inline unsigned long _stl_next_prime(unsigned long n)
{
	static const int _stl_num_primes = 28;
	static const unsigned long _stl_prime_list[_stl_num_primes] = {
		53, 97, 193, 389, 769,
		1543, 3079, 6151, 12289, 24593,
		49157, 98317, 196613, 393241, 786433,
		1572869, 3145739, 6291469, 12582917, 25165843,
		50331653, 100663319, 201326611, 402653189, 805306457,
		1610612741, 3221225473, 4294967291
	};
	const unsigned long* first = _stl_prime_list;
	const unsigned long* last = _stl_prime_list + _stl_num_primes;
	const unsigned long* pos = lower_bound(first, last, n);//[first,second) >=n
	return pos == last ? *(last - 1) : *pos;
}


//哈希桶
namespace hash_bucket
{
	template<class T>
	struct HashNode
	{
		T _data;
		HashNode<T>* _next;

		HashNode(const T& data)
			:_data(data)
			,_next(nullptr)
		{}
	};

	//前置声明
	template<class K, class T, class KeyOfT, class Hash>
	class HashTable;

	template<class K, class T, class Ref, class Ptr, class KeyOfT, class Hash>
	struct HTIterator
	{
		typedef HashNode<T> Node;
		typedef HashTable<K, T, KeyOfT, Hash> HT;
		typedef HTIterator<K, T, Ref, Ptr, KeyOfT, Hash> Self;

		Node* _node;
		const HT* _ht;

		HTIterator(Node* node, const HT* ht)
			:_node(node)
			, _ht(ht)
		{}

		Ref operator*()
		{
			return _node->_data;
		}

		Ptr operator->()
		{
			return &_node->_data;
		}

		bool operator==(const Self& s)
		{
			return _node == s._node;
		}

		bool operator!=(const Self& s)
		{
			return _node != s._node;
		}

		Self& operator++()
		{
			//当前桶还有数据，走下一个节点
			if (_node->_next)
			{
				_node = _node->_next;
			}
			//当前桶走完了，找下一个不为空的桶
			else
			{
				KeyOfT kot;
				Hash hash;
				size_t hashi = hash(kot(_node->_data)) % _ht->_tables.size();
				++hashi;
				while (hashi < _ht->_tables.size())
				{
					_node = _ht->_tables[hashi];

					if (_node)
						break;
					else
						++hashi;
				}

				//走完所有桶，end()给的空_node
				if (hashi == _ht->_tables.size())
				{
					_node = nullptr;
				}
			}

			return *this;
		}
	};

	template<class K, class T, class KeyOfT, class Hash>
	class HashTable
	{
		//友元声明  允许访问struct HTIterator
		template<class K, class T, class Ref, class Ptr, class KeyOfT, class Hash>
		friend struct HTIterator;

		typedef HashNode<T> Node;
	public:
		typedef HTIterator<K, T, T&, T*, KeyOfT, Hash> Iterator;
		typedef HTIterator<K, T, const T&, const T*, KeyOfT, Hash> ConstIterator;

		Iterator Begin()
		{
			//哈希表为空
			if (_n == 0)
				return End();

			//找第一个不为空的桶
			for (size_t i = 0; i < _tables.size(); ++i)
			{
				Node* cur = _tables[i];
				if (cur)
				{
					return Iterator(cur, this);
				}
			}

			//走完所有桶
			return End();
		}

		Iterator End()
		{
			return Iterator(nullptr, this);
		}

		ConstIterator Begin() const
		{
			if (_n == 0)
				return End();

			for (size_t i = 0; i < _tables.size(); ++i)
			{
				Node* cur = _tables[i];
				if (cur)
				{
					return ConstIterator(cur, this);
				}
			}

			return End();
		}

		ConstIterator End() const
		{
			return ConstIterator(nullptr, this);
		}


		HashTable()
			:_tables(_stl_next_prime(0), nullptr)
			, _n(0)
		{}

		HashTable(const HashTable& ht)
		{
			_tables.resize(ht._tables.size(), nullptr);//初始化N个空节点
			_n = ht._n;

			//遍历源哈希表的每个桶，进行深拷贝
			for (size_t i = 0; i < ht._tables.size(); ++i)
			{
				Node* cur = ht._tables[i];
				Node* newHead = nullptr;
				Node* tail = nullptr;

				//拷贝链表中的每个节点
				while (cur)
				{
					Node* newnode = new Node(cur->_data); //深拷贝节点

					//尾插
					if (newHead == nullptr)
					{
						newHead = newnode;
						tail = newnode;
					}
					else
					{
						tail->_next = newnode;
						tail = tail->_next;
					}

					cur = cur->_next;
				}

				_tables[i] = newHead;//将新链表头指针存入当前哈希表
			}
		}

		void Swap(HashTable& ht)
		{
			_tables.swap(ht._tables);
			swap(_n, ht._n);
		}
		
		HashTable& operator=(HashTable ht)
		{
			Swap(ht);

			return *this;
		}

		~HashTable()
		{
			//释放每个桶
			for (size_t i = 0; i < _tables.size(); ++i)
			{
				Node* cur = _tables[i];
				while (cur)
				{
					Node* next = cur->_next;
					delete cur;

					cur = next;
				}

				_tables[i] = nullptr;
			}
		}

		pair<Iterator,bool> Insert(const T& data)
		{
			//避免重复值插入	
			KeyOfT kot;
			Iterator it = Find(kot(data));
			if (it != End())
				return { it,false };

			Hash hash;

			//负载因子=1时扩容
			if (_n == _tables.size())
			{
				vector<Node*> newTable(_stl_next_prime(_tables.size() + 1),nullptr);
				for (size_t i = 0; i < _tables.size(); ++i)
				{
					Node* cur = _tables[i];
					while (cur)
					{
						Node* next = cur->_next;
						//原数据头插到新表
						size_t hashi = hash(kot(cur->_data)) % newTable.size();
						cur->_next = newTable[hashi];
						newTable[hashi] = cur;

						cur = next;
					}

					_tables[i] = nullptr;//对应旧表清空
				}

				_tables.swap(newTable);
			}

			size_t hashi = hash(kot(data)) % _tables.size();
			//头插
			Node* newnode = new Node(data);
			newnode->_next = _tables[hashi];//新节点指向原链表头
			_tables[hashi] = newnode;//newnode成为新链表头
			++_n;

			return { Iterator(newnode,this),true };
		}


		Iterator Find(const K& key) 
		{
			KeyOfT kot;
			Hash hash;
			size_t hashi = hash(key) % _tables.size();
			Node* cur = _tables[hashi];
			while (cur)
			{
				if (kot(cur->_data) == key)
				{
					return Iterator(cur, this);
				}

				cur = cur->_next;
			}

			return End();
		}

		bool Erase(const K& key)
		{
			KeyOfT kot;
			Hash hash;
			size_t hashi = hash(key) % _tables.size();

			Node* prev = nullptr;
			Node* cur = _tables[hashi];
			while (cur)
			{
				if (kot(cur->_data) == key)
				{
					//头节点
					if (prev == nullptr)
					{
						_tables[hashi] = cur->_next;
					}
					//中间节点
					else
					{
						prev->_next = cur->_next;
					}

					delete cur;
					--_n;

					return true;
				}
				else
				{
					prev = cur;
					cur = cur->_next;
				}
			}

			//节点不存在
			return false;
		}

	private:
		vector<Node*> _tables;//指针数组
		size_t _n = 0;
	};
}


